<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\Diagnose;

use App\Modules\Bill\Models\Bill;
use Illuminate\Support\Facades\Log;
use App\Modules\Order\Services\OrderService;
use App\Modules\Diagnose\Services\GraphicService;
use App\Modules\Diagnose\Services\OrderDiagnoseService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 图文问诊
 * Class GraphicController
 * @package App\Http\Controllers\Api\Home
 */
class GraphicController extends Controller
{
    /**
     * 问诊列表
     */
    public function getList(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 16;
        $size = $request->input('size',15);
        $dataList = GraphicService::recordsList($user_id,$size);
        $data = [
            'list'  => $dataList,
            'domain'=> env('MINI_APP_DOMAIN'),
            'home_domain'=> env('HOME_DOMAIN'),
        ];
        return response()->success($data);
    }

    /**
     * 我的提问详情
     */
    public function getQuestions(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 16;
        $size = $request->input('size',15);
        $group_id = $request->input('group_id');
        if ( empty($group_id) ) return response()->error("PARAM_EMPTY");
        //获取问题
        $questionsGet = GraphicService::get($user_id,$group_id);
        //获取回复内容
        $result = GraphicService::getDetails($user_id,$group_id,$size);
        $data = [
            'questions' => $questionsGet,
            'list'      => $result,
            'domain'    => env('MINI_APP_DOMAIN'),
            'home_domain'=> env('HOME_DOMAIN'),
        ];
        return response()->success($data);
    }

    /**
     * 追加提问
     */
    public function additional(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 16;
        $group_id = $request->input('group_id');
        $content = $request->input('content');
        $imgs = $request->input('image_source','');
        if ( empty($group_id) || empty($content) ) return response()->error("PARAM_EMPTY");
        $result = GraphicService::get($user_id,$group_id);
        if ( empty($result) ) return response()->error("PARAM_ERROR");
        //判断是否在24小时之内（只在24小时之内才能追问）
        $result = $result->toArray();
        $dateTime = strtotime("+1 day",strtotime($result['created_at']));
        if ( time() > $dateTime ) return response()->error("OVER_TIME_ERROR");
        $dataInsertArr = [
            'user_id'               => $user_id,
            'doctor_id'             => $result['doctor_id'],
            'group_id'              => $group_id,
            'initiator_identity'    => 2,
            'type'                  => 2,
            'content'               => $content,
            'accessory'             => empty($imgs) ? '' : $imgs,
        ];
        DB::beginTransaction();
        try{
            //添加追加问题数据
            $dataInsert = GraphicService::add($dataInsertArr);
            if ( empty($dataInsert) ) throw new \Exception('ADD_FAILURE');
            //修改父级状态
            $dataUpdate = GraphicService::updateSave(['id'=>$group_id,'status'=>3]);
            if ( empty($dataUpdate) ) throw new \Exception('ADD_FAILURE');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error($e->getMessage());
        }
        return response()->success();
    }

    /**
     * 问诊提问
     */
    public function questions(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 16;
        $doctor_id = $request->input('doctor_id');
        $content = $request->input('content');
        $amount = $request->input('amount');
        $type = $request->input('type');
        $imgs = $request->input('image_source','');
        $payment_source = $request->input('payment_source');
        $client_ip = $request->getClientIp();
        if ( empty($content) || empty($doctor_id) || empty($type) || empty($amount) || !is_numeric($amount) ) return response()->error("PARAM_EMPTY");
        if ( $type == 1 && empty($payment_source) ) return response()->error("PARAM_EMPTY");
        $balance = $this->getLoginUser()->balance;
//        $balance = 5;
        if ( $type == 2 && $balance < $amount )  return response()->error("BALANCE_DEFICIENCY");
        $amount = $type == 1 ? 2 : $amount;     //固定金额 2
//        $group_id = time();
        $dataTime = date('Y-m-d H:i:s',time());
        $dataInsertArr = [
            'user_id'           => $user_id,
            'doctor_id'         => $doctor_id,
            'group_id'          => 0,
            'initiator_identity'=> 2,
            'type'              => 2,
            'content'           => $content,
            'accessory'         => empty($imgs) ? '' : $imgs,
            'created_at'        => $dataTime,
            'updated_at'        => $dataTime,
        ];
        DB::beginTransaction();
        try{
            $dataInsertArr['status'] = $type == 2 ? 1 : 0;
            //添加问诊信息
            $diagnoseID = DB::table('diagnose')->insertGetId($dataInsertArr);
            if ( empty($diagnoseID) ) throw new \Exception('ADD_FAILURE');
            //添加订单信息
            $trade_no = getOrder();
            $orderInsertArr = [
                'user_id'           => $user_id,
                'trade_no'          => $trade_no,
                'diagnose_id'       => $diagnoseID,
                'diagnose_group_id' => 0,
                'type'              => $type,
                'amount'            => $amount,
                'pay_time'          => $dataTime,
                'create_ip'         => $client_ip,
            ];
            if ( $type == 2 ) {     //金币支付
                $orderInsertArr['pay_end_at']  = $dataTime;
                $orderInsertArr['status'] = 1;
                $orderInsert = OrderDiagnoseService::add($orderInsertArr);
                if ( empty($orderInsert) ) throw new \Exception('ADD_FAILURE');
                //扣除用户金币
                $userSave = DB::table('users')->where('id',$user_id)->decrement('balance', $amount);
                if ( empty($userSave) ) throw new \Exception('ADD_FAILURE');
                //添加账单信息
                $billInsertArr = [
                    'user_id'   => $user_id,
                    'bill_no'   => getOrder(),
                    'trade_no'  => $trade_no,
                    'source'    => 2,
                    'type'      => 2,
                    'amount'    => $amount
                ];
                $billInsert = Bill::add($billInsertArr);
                if ( empty($billInsert) ) throw new \Exception('ADD_FAILURE');
                $payResultInfo = [];
            }else{                  //金额支付
                $orderInsertArr['payment_source'] = $payment_source;
                $orderInsertArr['status'] = 0;
                $orderInsert = OrderDiagnoseService::add($orderInsertArr);
                if ( empty($orderInsert) ) throw new \Exception('ADD_FAILURE');
                //统一下单
                switch ($payment_source) {
                    case 'MINI_WECHAT': //小程序
                        $amount = 1;               //TODO 正式上线支付金额改为实际金额
//                        $amount = $amount * 100;
                        $pay_data = array(
                            'price'=> $amount,
                            'create_ip'=> $client_ip,
                            'openid'=> $this->getLoginUserWechatOpenId(),
                            'body' => '图文咨询服务',
                            'detail' => '图文咨询服务',
                            'trade_no' => $trade_no,
                            'remark' => '图文咨询服务',
                            'notify_url' => env('GRAPHIC_PAY_CALL_BACK_URL'),
                        );
                        $payResultInfo = OrderService::create_unpay($pay_data);
                        if( empty($payResultInfo) || !isset($payResultInfo['appId']) || !isset($payResultInfo['package'])) {
                            Log::info('CREATE_ORDER_ERROR:'.json_encode($payResultInfo));
                            throw new \Exception('CREATE_ORDER_ERROR');
                        }
                        break;
                    case 'ALIPAY':      //支付宝
                        $amount = '0.01';
                        $payResultInfo = OrderService::alipay_pay($trade_no,$amount,'图文咨询',env('GRAPHIC_ALIPAY_CALL_BACK_URL')); //TODO 正式上线支付金额改为实际金额
                        if ( empty($payResultInfo) ) {
                            Log::info('CREATE_ORDER_ERROR:'.json_encode($payResultInfo));
                            throw new \Exception('CREATE_ORDER_ERROR');
                        }
                        break;
                    case 'WECHAT':      //微信支付
                        break;
                    default:
                        throw new \Exception('PARAM_ERROR');
                        break;
                }
                $payResultInfo['order'] = $trade_no;
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error($e->getMessage());
        }
        return response()->success($payResultInfo);
    }

    //上传图片
    public function uploadImg($img,$path='/uploads/graphic/'){
        $filePath =[];
        foreach ($img as $key => $value) {
            // 判断图片上传中是否出错
            if (!$value->isValid()) return response()->error("UPLOAD_ERROR");
            if(!empty($value)){         //防止没有多文件上传的情况
                $destinationPath = $path.date('Y-m-d');                              // public文件夹下面uploads/xxxx-xx-xx 建文件夹
                $extension = $value->getClientOriginalExtension();                           // 上传文件后缀
                $fileName = date("YmdHis",time()).mt_rand(1000,9999).'.'.$extension; // 重命名
                $value->move(public_path().$destinationPath, $fileName);                     // 保存图片
                $filePath[] = $destinationPath.'/'.$fileName;

            }
        }
        return $filePath;
    }

}
























